package createJfinalFileV1.write;

import createJfinalFileV1.Config;
import createJfinalFileV1.build.baseBuilder.BaseBuilder;

import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 马洁
 * @date 2019/11/15 - 18:20
 */
public class FileWrite {
    private static String[] contentType = new String[Config.fileSuffix.length];

    private String packageName;
    private String prefix;
    private PrintWriter[] printWriters;

    static {
        for (int i = 0; i < contentType.length; i++) {
            contentType[i] = Config.BUILD_PACKAGE + "Builder" + Config.fileSuffix[i];
        }
    }

    public FileWrite(String packageName, String prefix, PrintWriter[] printWriters) {
        this.packageName = packageName;
        this.prefix = prefix;
        this.printWriters = printWriters;
    }

    public BaseBuilder[] getBuilders() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        BaseBuilder[] builders = new BaseBuilder[Config.fileSuffix.length];

        Class[] classes = new Class[Config.fileSuffix.length];
        for (int i = 0; i < builders.length; i++) {
            Constructor<BaseBuilder> constructor = (Constructor<BaseBuilder>)
                    Class.forName(contentType[i])
                            .getConstructor(String.class, String.class);

            builders[i] = constructor.newInstance(packageName, prefix);
        }

        return builders;
    }

    public boolean write() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        BaseBuilder[] builders = getBuilders();

        for (int i = 0; i < printWriters.length; i++) {
            String result = new FileContent(builders[i]).getContent();
            printWriters[i].write(result);
            printWriters[i].close();
        }

        return true;
    }
}
